// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/resolved/pass_manager.h>
#include <cantor/resolved/stmt.h>
#include <turbo/log/logging.h>

namespace cantor::resolved {

    turbo::Status PassManager::initialize(const cantor::pb::ast::Statement &stmt, std::unique_ptr<PassContext> && context) {
        if (_initialized) {
            return turbo::already_exists_error("already initialized");
        }
        if (context == nullptr) {
            return turbo::data_loss_error("context is null");
        }

        _resolved_ctx.set_stmt(stmt);
        _resolved_ctx.pass_context = std::move(context);
        _initialized = true;
        _timer.reset();
        return  turbo::OkStatus();
    }

    void PassManager::reset_timer() {
        KCHECK(_initialized)<<"must be initialized before reset_timer()";
        _timer.reset();
    }

    turbo::Status PassManager::run_pass(PassBase *pass) {
        if (pass == nullptr) {
            return turbo::data_loss_error("pass is null");
        }
        pass->context = &_resolved_ctx;
        _resolved_ctx.appy_pass(pass->name());
        return  ResolvedStmt::accept(pass);
    }
}  // namespace cantor::resolved
